<template>
  <div class="">
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <e-heading>
        {{ (!id ? '新建' : '修改') + '赞助计划'}}
        <small>
          <span>1.创建赞助品牌</span>
          <span>2.创建投放计划</span>
          <span>3.通过平台审核</span>
          <span>4.匹配项目</span>
          <span>5.签订协议</span>
          <span>6.投放成功</span>
        </small>
      </e-heading>
      <e-heading grade="2">基本信息</e-heading>
      <el-form
        ref="form"
        :rules="rules"
        v-bind="getFormProps({labelWidth:'160px'})"
        class="train-form">
        <el-form-item label="赞助品牌："
          prop="brandId"
          :rules="{ required: true, message: '请选择一个赞助品牌'}">
          <el-col :span="20">
            <template>
              <el-select
                :disabled="id && form.auditStatus != 0"
                v-model="form.brandId"
                placeholder="请选择一个赞助品牌">
                <el-option
                  v-for="item in dict.brandList.data"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-col>
        </el-form-item>

        <el-form-item label="赞助计划名称："
          prop="planName"
          :rules="{ required: true, message: '计划名称不能为空'}">
          <el-col :span="20">
            <div class="remaining-box">
              <el-input
                :disabled="id && form.auditStatus != 0"
                placeholder="请输入赞助名称"
                v-model="form.planName"
                :maxlength="40"
                number-word />
            </div>
          </el-col>
        </el-form-item>
        <el-form-item
          label="投放项目（多选）"
          prop="projectType"
          :rules="{ required: true, message: '请选择项目类型'}">
          <el-col :span="20">
            <el-select
              class="input-block"
              v-model="form.projectType"
              @change="handlechangeselect()"
              filterable
              multiple>
              <el-option
                v-for="x in dict.sportType.data"
                :key="x.value"
                :label="x.label"
                :value="x.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="赞助方式："
          prop="sponsorType"
          :rules="{ required: true, message: '请选择赞助方式'}">
          <el-col :span="20">
            <template>
              <el-select
                v-model="form.sponsorType"
                placeholder="请选择赞助方式">
                <el-option
                  v-for="item in dict.sponsorType.data"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-col>
        </el-form-item>
        <el-form-item label="总预算："
          prop="money"
          :rules="[
            {required: true, message: '请输入赞助金额'},
            validator.rule.isIntadd
          ]">
          <el-col :span="20">
            <div class="remaining-box">
              <el-input
                class="w300"
                :maxlength="5"
                placeholder=""
                v-model="form.money"/>
              <span class="unit">万元起</span>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="投放时间："
          prop="startTime"
          :rules="[
            { required: true, trigger: 'blur', validator: rules.hhv},
          ]">
          <template>
            <div class="time-list">
              <el-date-picker
                v-model="form.startTime"
                type="month"
                :picker-options="startTimeOptions"
                placeholder="选择月">
              </el-date-picker>
            </div>
            <span> ~ </span>
            <div class="time-list">
              <el-date-picker
                v-model="form.endTime"
                type="month"
                placeholder="选择月"
                :picker-options="endTimeOptions"
                @change="form.endTime = lastDay(form.endTime)">
              </el-date-picker>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="投放地域(多选)："
          prop="planAreaList">
          <el-col :span="20">
            <template>
              <el-select
                class="input-block"
                v-model="form.planAreaList"
                placeholder="全国"
                @change="handlechangeselect()"
                filterable
                multiple>
                <el-option
                  v-for="item in areaJson.province"
                  :key="item.areaId"
                  :label="item.title"
                  :value="item.areaId">
                </el-option>
              </el-select>
            </template>
          </el-col>
        </el-form-item>
        <el-form-item label="目标人群："
          prop="targetGroup">
          <el-col :span="20">
            <template>
              <el-select
                v-model="form.targetGroup"
                placeholder="请选择目标人群">
                <el-option
                  v-for="item in dict.targetGroup.data"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-col>
        </el-form-item>
        <el-form-item label="赞助目的："
          prop="sponsorPurpose"
          :rules="{ required: true, message: '请选择赞助目的'}">
          <el-col :span="20">
            <template>
              <el-select
                v-model="form.sponsorPurpose"
                placeholder="请选择赞助目的">
                <el-option
                  v-for="item in dict.sponsorPurpose.data"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-col>
        </el-form-item>
        <el-form-item label="投放诉求："
          prop="plainDemand">
          <el-col :span="20">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3}"
              :maxlength="300"
              placeholder=" "
              v-model="form.plainDemand"
              number-word />
          </el-col>
        </el-form-item>
        <div class="button-box">
          <el-button type="primary" native-type="submit" :loading="loading && loadingId == 1">确定提交</el-button>
          <!--<el-button v-if="!id" :loading="loading && loadingId == 0" @click="submit(0)">保存草稿</el-button>-->
          <el-button v-if="id" @click="submit(3)">放弃修改</el-button>
        </div>
      </el-form>
    </div>
  </div>

</template>

<script>
  import { mapGetters } from 'vuex'
  import api from 'api/sponsor'
  import filters from '../../../filters'
  import areaJson from '../../../../static/area.json'
  import validator from 'utils/validator'
  import {form} from 'utils/mixins' // 引入form mixin
  export default {
    mixins: [form],
    computed: {
      ...mapGetters({
        dict: 'sponsor_dict'
      })
    },
    data () {
      let isCertify
      let that = this
      return {
        isCertify,
        validator,
        id: this.$route.params.id,
        loading: false,
        areaJson,
        loadingId: '',
        form: {
          brandId: '', // 品牌Id
          planName: '', // 赞助计划名称
          projectType: [], // 投放项目列表
          planAreaList: [], // 投放区域列表
          startTime: this.firstDay(new Date()), // 投放开始时间
          endTime: this.lastDay(new Date()), // 投放结束时间
          sponsorType: '', // 赞助方式
          money: '', // 总预算
          targetGroup: '', // 目标人群
          sponsorPurpose: '', // 赞助目的
          plainDemand: '', // 投放诉求
          auditStatus: ''
        },
        rules: {
          hhv: (rule, value, callback) => { // 时间验证
            let val1 = this.form.startTime
            let val2 = this.form.endTime
            if (!val1 || !val2) {
              return callback(new Error('投放时间不能为空'))
            }
            let now = parseInt(filters.FormatDate(new Date(), 'yyyyMM'))
            if (now > parseInt(filters.FormatDate(val1, 'yyyyMM'))) {
              return callback(new Error('起始时间不能小于当前时间'))
            }
            if (val1 && val2) {
              return val1 > val2 ? callback(new Error('结束时间必须大于开始时间')) : callback()
            }
            return callback()
          }
        },
        startTimeOptions: { // startTime 规则，用于处理endtime的禁止时间
          disabledDate (time) {
            var date = new Date()
            date.setDate(1)
            return time.getTime() <= date - 3600 * 24 * 1000
          }
        },
        endTimeOptions: { // 用于处理endtime的禁止时间 规则，用于处理startTime的禁止时间
          disabledDate (time) {
            if (that.form.startTime) {
              return time.getTime() < that.form.startTime.getTime() + 1000 * 24 * 3600
            } else {
              return true
            }
          }
        }
      }
    },
    mounted () {
      if (this.id) {
        // 编辑
        this.getdetailed(this.id)
      }
      this.$store.dispatch('sponsor_dict', 'sportType') // sportType获取字典数据
      this.$store.dispatch('sponsor_dict', 'brandList') // brandList获取字典数据
    },
    methods: {
      getdetailed (id) { // 编辑 获取数据
        api.support_detailed({planId: id}).then((json) => {
          if (json.data.auditStatus === 1) this.$router.push({path: '/sponsor/support'})
          json.data.money /= 1000000
          json.data.planAreaList = json.data.planAreaList[0] === 0 ? [] : json.data.planAreaList // 地理区域 全国为0
          json.data.startTime = new Date(json.data.startTime) // 时间戳处理
          json.data.endTime = new Date(json.data.endTime) // 时间戳处理
          this.form = json.data
        }, () => {
          this.$router.push({path: '/sponsor/support'}) // 接口错误，跳回
        })
      },
      submit (type = 1) {
        // 提交   type  1提交 0草稿 3放弃
        this.loadingId = type
        if (type === 3) {
          this.$router.push({path: '/sponsor/support'})
          return
        }
        let form = Object.assign({}, this.form)
        form.startTime = Date.parse(form.startTime)
        form.endTime = Date.parse(this.lastDay(form.endTime))
        form.auditStatus = type // 设置保存、草稿状态
        if (this.id) {
          form.planId = this.id
          api.support_edit(form, {context: this, successMsg: 'none'}).then((json) => {
            this.handleSubmitSuccess(type, form.id)
          })
        } else {
          api.support_add(form, {context: this, successMsg: 'none'}).then((json) => {
            this.handleSubmitSuccess(type)
          })
        }
      },
      lastDay (date) { // 计算当月最后一天
        let now = {
          y: parseInt(filters.FormatDate(date, 'yyyy')),
          m: parseInt(filters.FormatDate(date, 'MM'))
        }
        if (now.m === 12) {
          now.y++
          now.m = 1
        } else {
          now.m++
        }
        let nextM = new Date(now.y + '-' + now.m + '-01 23:59:59')
        nextM.setDate(nextM.getDate() - 1) // 设置天数 -1 天
        return nextM
      },
      firstDay (date) { // 计算当月第一天
        let time = new Date(filters.FormatDate(date, 'yyyy-MM') + '-01 00:00:00')
        time.setDate(time.getDate()) // 设置天数 -1 天
        return time
      },
      handleSubmitSuccess (type) { // 成功提示框
        let that = this
        let text = [
          {
            title: (this.id ? '修改' : '新建') + '赞助计划草稿成功!',
            text: '草稿保存到赞助计划列表中！'
          },
          {
            title: (this.id ? '修改' : '新建') + '赞助计划成功!',
            text: '我们会在3个工作之内完成审核，请耐心等待！'
          }
        ]
        this.$confirm(text[type].text, text[type].title, {
          type: 'success',
          showCancelButton: false,
          callback () {
            that.$router.push({path: '/sponsor/support'})
          }
        })
      },
      handlechangeselect (value, item) {
        this.$refs.form.validateField('projectType')
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .heading small span{
    margin: 0 10px;
  }
  .unit{
    margin-left: 10px;
  }
  .w300{
    width: 300px;
  }
  input[type="number"]::-webkit-outer-spin-button,
  input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"]{
    -moz-appearance: textfield;
  }
  .time-list{
    display: inline-block;
  }
</style>
